<template>
  <div class="qa-view">
    <!-- 左侧历史对话栏 -->
    <div class="sidebar">
      <div class="sidebar-header">
        <h2>历史对话</h2>
        <button class="new-chat-btn" @click="startNewChat">
          <span class="plus-icon">+</span> 新建对话
        </button>
      </div>
      
      <div class="history-list">
        <div 
          v-for="(chat, index) in chatHistory" 
          :key="index" 
          class="history-item"
          :class="{ 'active': currentChatIndex === index }"
          @click="selectChat(index)"
        >
          <div class="history-title">{{ getChatTitle(chat) }}</div>
          <div class="history-time">{{ chat.time || '刚刚' }}</div>
        </div>
        
        <div v-if="chatHistory.length === 0" class="no-history">
          暂无历史对话记录
        </div>
      </div>
    </div>

    <div class="chat-container">
      <!-- 消息列表 -->
      <div class="messages-container" ref="messagesContainer">
        <ChatMessage 
          v-for="(message, index) in messages" 
          :key="index" 
          :content="message.content" 
          :type="message.type"
          @content-updated="scrollToBottom"
        />
      </div>
      
      <!-- 输入区域 -->
      <div class="input-area">
        <div class="input-container" :class="{ 'loading': isLoading }">
          <textarea 
            v-model="question" 
            placeholder="输入您的法律问题..." 
            @keydown.enter.prevent="handleEnterKey"
            :disabled="isLoading"
            ref="inputField"
            rows="1"
          ></textarea>
          
          <div class="input-buttons">
            <button 
              class="secondary icon-button"
              @click="clearInput" 
              :disabled="isLoading"
              title="清空输入"
            >
              <span class="icon">✕</span>
            </button>
            <button 
              class="primary send-button"
              @click="sendMessage" 
              :disabled="!canSend || isLoading"
            >
              <span v-if="!isLoading">发送</span>
              <span v-else class="loading-icon">⋯</span>
            </button>
          </div>
        </div>
        <div class="input-helper">
          <span v-if="!isLoading">按 <kbd>Enter</kbd> 发送消息</span>
          <span v-else class="loading-text">正在处理...</span>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { mapState, mapActions } from 'vuex';
import ChatMessage from '@/components/ChatMessage.vue';

export default {
  name: 'QAView',
  components: {
    ChatMessage
  },
  data() {
    return {
      question: '',
      autoScrollEnabled: true,  // 默认启用自动滚动
      chatHistory: [],
      currentChatIndex: -1
    };
  },
  computed: {
    ...mapState({
      messages: state => state.qaMessages,
      isLoading: state => state.isLoading
    }),
    canSend() {
      return this.question.trim().length > 0;
    }
  },
  methods: {
    ...mapActions([
      'sendQuestion',
      'resetChat'
    ]),
    handleEnterKey(e) {
      // 按下Enter且未按下Shift时发送消息
      if (!e.shiftKey && this.canSend && !this.isLoading) {
        this.sendMessage();
      }
    },
    sendMessage() {
      // 确保传递的是字符串
      const questionText = String(this.question || '');
      if (questionText.trim()) {
        // 先在当前对话中保存这个问题用于展示
        const currentQuestion = questionText;
        
        // 发送问题到API
        this.sendQuestion(questionText);
        
        // 保存到历史记录中 - 延迟执行确保消息已更新
        setTimeout(() => {
          this.saveToHistory(currentQuestion);
        }, 100);
        
        this.question = '';
        // 发送消息时，重新启用自动滚动
        this.autoScrollEnabled = true;
        this.scrollToBottom();
      }
    },
    clearInput() {
      this.question = '';
      this.$refs.inputField.focus();
    },
    startNewChat() {
      this.resetChat();
      this.question = '';
      this.currentChatIndex = -1;
    },
    saveToHistory(currentQuestion) {
      // 获取当前时间作为时间戳
      const now = new Date();
      const formattedTime = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}-${String(now.getDate()).padStart(2, '0')} ${String(now.getHours()).padStart(2, '0')}:${String(now.getMinutes()).padStart(2, '0')}`;
      
      // 如果当前是选中的对话，更新它
      if (this.currentChatIndex >= 0 && this.chatHistory.length > 0) {
        this.chatHistory[this.currentChatIndex] = {
          messages: [...this.messages],
          lastQuestion: currentQuestion || this.question,
          firstQuestion: this.chatHistory[this.currentChatIndex].firstQuestion || currentQuestion,
          time: formattedTime
        };
      } else {
        // 否则创建新对话
        this.chatHistory.unshift({
          messages: [...this.messages],
          lastQuestion: currentQuestion || this.question,
          firstQuestion: currentQuestion,
          time: formattedTime
        });
        this.currentChatIndex = 0;
      }
      
      // 保存到本地存储
      this.saveHistoryToLocalStorage();
      
      // 强制更新视图
      this.$forceUpdate();
    },
    selectChat(index) {
      if (this.currentChatIndex === index) return;
      
      // 先保存当前对话
      if (this.currentChatIndex >= 0) {
        this.saveToHistory();
      }
      
      this.currentChatIndex = index;
      const selectedChat = this.chatHistory[index];
      
      // 加载选中的对话内容
      this.$store.state.qaMessages = [...selectedChat.messages];
      this.question = selectedChat.lastQuestion || '';
      
      this.$nextTick(() => {
        this.scrollToBottom();
      });
    },
    getChatTitle(chat) {
      // 使用存储的第一个问题作为标题
      if (chat.firstQuestion) {
        return chat.firstQuestion.length > 20 
          ? chat.firstQuestion.substring(0, 20) + '...' 
          : chat.firstQuestion;
      }
      
      // 或者找到第一条用户消息作为标题
      const userMessage = chat.messages.find(msg => msg.type === 'user');
      if (userMessage) {
        return userMessage.content.length > 20 
          ? userMessage.content.substring(0, 20) + '...' 
          : userMessage.content;
      }
      
      return '新对话';
    },
    saveHistoryToLocalStorage() {
      try {
        localStorage.setItem('chatHistory', JSON.stringify(this.chatHistory.slice(0, 20))); // 最多保存20条记录
        console.log('保存历史记录到本地存储，数量：', this.chatHistory.length);
      } catch (e) {
        console.error('无法保存历史记录到本地存储:', e);
      }
    },
    loadHistoryFromLocalStorage() {
      try {
        const savedHistory = localStorage.getItem('chatHistory');
        if (savedHistory) {
          this.chatHistory = JSON.parse(savedHistory);
          console.log('从本地存储加载历史记录，数量：', this.chatHistory.length);
        }
      } catch (e) {
        console.error('无法从本地存储加载历史记录:', e);
      }
    },
    scrollToBottom() {
      // 只有当自动滚动启用时才滚动
      if (this.autoScrollEnabled && this.$refs.messagesContainer) {
        this.$nextTick(() => {
          const container = this.$refs.messagesContainer;
          container.scrollTop = container.scrollHeight;
        });
      }
    },
    handleScroll() {
      if (this.$refs.messagesContainer) {
        const container = this.$refs.messagesContainer;
        // 检测用户是否已经滚动到接近底部的位置
        const isAtBottom = container.scrollHeight - container.scrollTop - container.clientHeight < 100;
        
        // 只有当用户手动滚动（不在底部）时才禁用自动滚动
        this.autoScrollEnabled = isAtBottom;
      }
    }
  },
  watch: {
    // 监听消息变化，自动滚动到底部
    messages: {
      handler(newMessages, oldMessages) {
        // 如果消息发生变化，可能是收到了回复，更新历史记录
        if (newMessages.length > oldMessages?.length) {
          this.saveToHistory();
        }
        this.scrollToBottom();
      },
      deep: true
    }
  },
  mounted() {
    // 加载历史记录
    this.loadHistoryFromLocalStorage();
    
    // 组件挂载后，聚焦到输入框
    this.$refs.inputField.focus();
    // 初始滚动到底部
    this.scrollToBottom();
    
    // 添加滚动事件监听，检测用户是否手动滚动
    if (this.$refs.messagesContainer) {
      this.$refs.messagesContainer.addEventListener('scroll', this.handleScroll);
    }
  },
  beforeUnmount() {
    // 组件卸载前，移除滚动事件监听
    if (this.$refs.messagesContainer) {
      this.$refs.messagesContainer.removeEventListener('scroll', this.handleScroll);
    }
  }
}
</script>

<style scoped>
.qa-view {
  display: flex;
  height: 100vh;
  background-color: #f0f2f5;
}

/* 侧边栏样式 */
.sidebar {
  width: 260px;
  background-color: white;
  border-right: 1px solid #e0e0e0;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.sidebar-header {
  padding: 16px;
  border-bottom: 1px solid #e0e0e0;
}

.sidebar-header h2 {
  font-size: 16px;
  margin: 0 0 15px 0;
  color: #333;
}

.new-chat-btn {
  width: 100%;
  padding: 8px 12px;
  background-color: #1890ff;
  color: white;
  border: none;
  border-radius: 4px;
  font-size: 14px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: background-color 0.3s;
}

.new-chat-btn:hover {
  background-color: #40a9ff;
}

.plus-icon {
  margin-right: 6px;
  font-size: 16px;
  font-weight: bold;
}

.history-list {
  flex: 1;
  overflow-y: auto;
  padding: 8px;
}

.history-item {
  padding: 12px;
  border-radius: 6px;
  cursor: pointer;
  margin-bottom: 4px;
  transition: background-color 0.2s;
  overflow: hidden;
}

.history-item:hover {
  background-color: #f5f5f5;
}

.history-item.active {
  background-color: #e6f7ff;
  border-left: 3px solid #1890ff;
}

.history-title {
  font-size: 14px;
  color: #333;
  margin-bottom: 4px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.history-time {
  font-size: 12px;
  color: #999;
}

.no-history {
  padding: 20px;
  text-align: center;
  color: #999;
  font-size: 14px;
}

/* 聊天区域样式 */
.chat-container {
  display: flex;
  flex-direction: column;
  flex: 1;
  height: 100%;
  background-color: transparent;
  overflow: hidden;
}

.messages-container {
  flex-grow: 1;
  overflow-y: auto;
  padding: 1.5rem;
  scroll-behavior: smooth; /* 添加平滑滚动效果 */
  background-color: white;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  margin: 20px;
  margin-bottom: 0;
  border-radius: 8px 8px 0 0;
}

.input-area {
  padding: 1rem 1.5rem;
  background-color: white;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  margin: 0 20px 20px 20px;
  border-radius: 0 0 8px 8px;
}

.input-container {
  display: flex;
  background-color: white;
  border: 1px solid #d9d9d9;
  border-radius: 8px;
  overflow: hidden;
  padding: 0.5rem;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.05);
  transition: border-color 0.3s;
}

.input-container.loading {
  border-color: #1890ff;
}

textarea {
  flex: 1;
  padding: 0.7rem;
  border: none;
  resize: none;
  font-family: inherit;
  font-size: 0.95rem;
  line-height: 1.5;
  min-height: 20px;
  max-height: 200px;
  overflow-y: auto;
}

textarea:focus {
  outline: none;
}

textarea:disabled {
  background-color: #f9fafb;
  cursor: not-allowed;
}

.input-buttons {
  display: flex;
  align-items: flex-end;
  gap: 8px;
  padding-right: 0.5rem;
}

.icon-button {
  width: 36px;
  height: 36px;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 0;
  background-color: transparent;
  color: #666;
  border: 1px solid #eaeaea;
  border-radius: 4px;
}

.icon-button:hover {
  background-color: #f5f5f5;
  color: #1890ff;
}

.send-button {
  padding: 0.5rem 1rem;
  height: 36px;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #1890ff;
  color: white;
  border-radius: 4px;
}

.send-button:hover {
  background-color: #40a9ff;
}

.send-button:disabled {
  background-color: #b3d9ff;
  cursor: not-allowed;
}

.icon {
  font-size: 1.1rem;
}

.loading-icon {
  animation: loading 1.5s infinite;
}

.input-helper {
  display: flex;
  justify-content: space-between;
  margin-top: 0.5rem;
  color: #888;
  font-size: 0.8rem;
}

kbd {
  display: inline-block;
  padding: 0.1rem 0.3rem;
  background-color: #f3f3f3;
  border: 1px solid #ddd;
  border-radius: 3px;
  box-shadow: 0 1px 1px rgba(0, 0, 0, 0.1);
  font-family: 'Courier New', monospace;
}

.loading-text {
  color: #1890ff;
}

@keyframes loading {
  0%, 100% { opacity: 0.3; }
  50% { opacity: 1; }
}

@media (max-width: 768px) {
  .qa-view {
    flex-direction: column;
  }
  
  .sidebar {
    width: 100%;
    height: auto;
    max-height: 40vh;
  }
  
  .messages-container,
  .input-area {
    margin: 10px;
  }
}
</style> 